package com.techstar.ats.codec;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;

public class StringCodec implements PrimitiveCodec<String> {
	public static final Charset GBK = Charset.forName("GBK");
	private final int length;

	public StringCodec(int length) {
		this.length = length;
	}

	public String get(ByteBuf buf) {
		byte[] s = new byte[this.length];
		buf.readBytes(s);

		int i = 0;
		for(; i < this.length && 0 != s[i]; ++i) {
		}

		return (new String(s, 0, i, GBK)).trim();
	}

	public void encode(ByteBuf buf, String value) {
		byte[] array = new byte[this.length];
		byte[] bytes = value.getBytes(GBK);
		System.arraycopy(bytes, 0, array, 0, Math.min(array.length, bytes.length));
		buf.writeBytes(array);
	}
}
